package cn.fan.filter;


import cn.fan.config.NoinspectionProperties;
import cn.fan.constants.TokenConstants;
import cn.fan.redis.JWTRedis;
import cn.fan.utils.JWTTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Autowired
    private JWTTokenUtil jwtTokenUtil;

    @Autowired
    private JWTRedis jwtRedis;

    @Autowired
    private NoinspectionProperties noinspectionProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        URI uri = request.getURI();

        // 设置不校验的地址
        // 到时候改到配置文件中去
//        if (uri.getPath().equals("/view/login") || uri.getPath().equals("/users/login") || uri.getPath().equals("/users/logout")){
//            return chain.filter(exchange);
//        }
//
//        // 测试，开放全部users请求
//        if ( (uri.getPath().startsWith("/view") && !uri.getPath().startsWith("/view/index")) || uri.getPath().startsWith("/js") || uri.getPath().startsWith("/css")){
//            return chain.filter(exchange);
//        }

        for (String url:noinspectionProperties.getUrls()){
//            System.out.println("urlProp:"+url);
//            System.out.println("uri.getPath():"+uri.getPath());
            if (uri.getPath().startsWith(url)){
                return chain.filter(exchange);
            }
//            System.out.println("需验证");
        }

        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if( null == cookies.get("token") ||
                cookies.size() == 0 ||
                !StringUtils.hasText(cookies.get("token").get(0).toString()) ){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        String token = cookies.get("token").get(0).toString();

        if (token.startsWith("token="))
            token = token.replaceFirst("token=","");

        System.out.println("token:"+token);

        // 查看与redis中存储的是否一致
        String userId = jwtTokenUtil.getUserIdFromToken(token);
        System.out.println("userid"+userId);
        if(!StringUtils.hasText(userId)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        String access_token = jwtRedis.getAccess_token(userId);
        System.out.println("access_token:"+access_token);
        if(!token.equals(access_token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 判断是否过期
        Boolean isJwtNotValid = jwtTokenUtil.isTokenExpired(token);
        if (isJwtNotValid){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 设置用户信息到请求
//        String userId = jwtTokenUtil.getUserIdFromToken(cookie);
        String username = jwtTokenUtil.getUserNameFromToken(token);
        addHeader(mutate, TokenConstants.USER_ID, userId);
        addHeader(mutate, TokenConstants.USER_NAME, username);

        // 内部请求来源参数清除
        removeHeader(mutate, TokenConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    @Override
    public int getOrder() {
        return -200;
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }
    /**
     * 内容编码
     *
     * @param str 内容
     * @return 编码后的内容
     */
    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, TokenConstants.UTF8);
        }
        catch (UnsupportedEncodingException e)
        {
            return "";
        }
    }
    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }
}
